package com.shenzw.common.utils;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * okHttp请求工具类
 *
 * @author shanwenxin
 * @date 2022/07/02
 */
public class OkHttpUtils {

    public static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");

    private static final Logger LOGGER = LoggerFactory.getLogger(OkHttpUtils.class);


    /**
     * POST请求方式
     *
     * @param url  链接url
     * @param json json数据串
     * @return String
     */
    public static String post(String url, String json) throws IOException {

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS) // 设置连接超时时间
                .readTimeout(30, TimeUnit.SECONDS) // 设置读取超时时间
                .build();

        RequestBody body = RequestBody.create(MediaType.parse("text/plain"), json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        if (response.body() != null) {
            return response.body().string();
        }
        return url;
    }


    /**
     * POST请求方式
     *
     * @param url  链接url
     * @param json json数据串
     * @return InputStream
     */
    public static InputStream postStream(String url, String json) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS) // 设置连接超时时间
                .readTimeout(30, TimeUnit.SECONDS) // 设置读取超时时间
                .build();

        RequestBody body = RequestBody.create(MEDIA_TYPE, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        if (response.body() != null) {
            return response.body().byteStream();
        }
        return null;
    }


    /**
     * GET请求方式
     *
     * @param url 链接url
     * @return String
     */
    public static String get(String url) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = client.newCall(request).execute();
        if (response.body() != null) {
            return response.body().string();
        }
        return url;
    }


    /**
     * GET请求方式
     *
     * @param url 链接url
     * @return InputStream
     */
    public static InputStream getStream(String url) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = client.newCall(request).execute();
        if (response.body() != null) {
            return response.body().byteStream();
        }
        return null;
    }


    public static void main(String[] args) {
        String url = "https://www.cnblogs.com/austinspark-jessylu/p/6873198.html";
        String result = "";
        try {
            result = OkHttpUtils.get(url);
        } catch (IOException e) {
            LOGGER.error("Main fun is error.", e);
        }
        LOGGER.info(result);
    }


    /**
     * 向指定 URL 发送POST方法的请求
     * 获取微信小程序 session_key
     *
     * @param url      发送请求的 URL
     * @param paramMap 请求参数
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, Map<String, ?> paramMap) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        StringBuilder param = new StringBuilder();

        for (String key : paramMap.keySet()) {
            param.append(key).append("=").append(paramMap.get(key)).append("&");
        }
        try {
            URLConnection conn = getUrlConnection(url);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                LOGGER.error("sendPost is error", ex);
            }
        }
        return result;
    }

    private static URLConnection getUrlConnection(String url) throws IOException {
        URL realUrl = new URL(url);
        // 打开和URL之间的连接
        URLConnection conn = realUrl.openConnection();
        // 设置通用的请求属性
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("Accept-Charset", "utf-8");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        return conn;
    }
}
